package com.itheima.controller;

import com.itheima.common.AuthThreadLocal;
import com.itheima.common.R;
import com.itheima.entity.ShoppingCart;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author HeiMa-sw
 * @Description 购物车表现层//TODO 17210
 * @Date 20:56 2022/6/9
 **/
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @PostMapping("/add")
    public R<ShoppingCart> shoppingCartAdd(@RequestBody ShoppingCart shoppingCart) {
        Boolean result = redisTemplate.opsForValue().setIfAbsent("lock_" + AuthThreadLocal.getAuth(), LocalDateTime.now().toString(),1, TimeUnit.SECONDS);
        if (!result){
            return R.error("皇上请慢点，臣妾受不了");
        }else {
            ShoppingCart shoppingCart1 = shoppingCartService.saveOne(shoppingCart);
            return R.success(shoppingCart1);
        }

    }

    @GetMapping("/list")
    public R<List<ShoppingCart>> shoppingCartList() {
        List<ShoppingCart> shoppingCarts = shoppingCartService.getList();
        return R.success(shoppingCarts);
    }

    @DeleteMapping("/clean")
    public R<String> shoppingCartClean() {
        shoppingCartService.cleanAll();
        return R.success("清空购物车成功");
    }

    @PostMapping("/sub")
    public R<String> shoppingCartSub(@RequestBody Map<String, String> map) {
        String dishId = map.get("dishId");
        String setmealId = map.get("setmealId");
        int rows = shoppingCartService.removeOne(dishId, setmealId);
        if (rows > 0) {
            return R.success("删除成功!");
        } else {
            return R.error("删除失败!");
        }
    }
}
